package com.qf.eduadmin.config;

import com.qf.eduadmin.mapper.TbPermissionDao;
import com.qf.eduadmin.mapper.jpa.TbUserRepository;
import com.qf.eduadmin.pojo.vo.TbPermission;
import com.qf.eduadmin.pojo.vo.TbUser;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Mr.Liu
 * @date 2021/12/29 20:24
 */

public class MyRealm extends AuthorizingRealm {

    @Autowired
    private TbUserRepository tbUserRepository;
    @Resource
    private TbPermissionDao tbPermissionDao;

    /**
     * 授权的操作,使用当前登录的用户名,查询该用户的权限
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String userName = (String) principalCollection.getPrimaryPrincipal();
        List<TbPermission> pers = tbPermissionDao.findPerByName(userName);
        Set set = new HashSet();
        for(TbPermission tbPermission : pers){
            set.add(tbPermission.getPermissionName());
        }
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addStringPermissions(set);
        return simpleAuthorizationInfo;
    }

    /**
     * 登录的操作,使用前台传输的用户名及密码进行登录操作
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String userName = (String) authenticationToken.getPrincipal();
        //通过用户名查询用户
        TbUser tbUser = tbUserRepository.findByUserName(userName);
        //System.out.println(tbUser);
        if(tbUser!=null){
            return new SimpleAuthenticationInfo(userName,tbUser.getPassWord(), ByteSource.Util.bytes(userName),getName());
        }
        return null;
    }
}
